mysql = require 'mysql'

module.exports = (settings) ->
  return unless settings.activate
  # if process.env.NODE_ENV is 'test'
  #   settings.database += '_test'
  connection = mysql.createConnection settings

  handleDisconnect = (myConnection) ->
    myConnection.on 'error', (err) ->
      console.log "Re-connecting lost connection: #{err.stack}"
      connection.destroy()
      connection = mysql.createConnection connection.config
      handleDisconnect connection
      connection.connect()

  handleDisconnect connection
  connection.connect()

  do interval = ->
    connection.ping()
    setTimeout interval, 60 * 60 * 1000

  connection
